package com.ruoyi.framework.web.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.ruoyi.common.core.domain.DTO.AuditBO;
import com.ruoyi.common.core.domain.DTO.InsertWithdrawalRecordBO;
import com.ruoyi.common.core.domain.DTO.WapTransferBO;
import com.ruoyi.common.core.domain.entity.UserPoints;
import com.ruoyi.common.core.domain.entity.UserPointsLog;
import com.ruoyi.common.core.domain.entity.UserZfbAccount;
import com.ruoyi.common.core.domain.entity.WithdrawalRecord;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.zfb.AlipayFundTransUniTransferWap;
import com.ruoyi.system.mapper.WithdrawalRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

@Component
@Transactional
public class WithdrawalRecordService {
    @Autowired
    private WithdrawalRecordMapper withdrawalRecordMapper;
    @Autowired
    private PointsService pointsService;
    @Autowired
    private AlipayFundTransUniTransferWap alipayFundTransUniTransferWap;
    @Autowired
    private UserZfbAccountService userZfbAccountService;

    public void insertWithdrawalRecord(InsertWithdrawalRecordBO insertWithdrawalRecordBO) {
        Long userId = insertWithdrawalRecordBO.getUserId();
        WithdrawalRecord withdrawalRecord = new WithdrawalRecord();
        withdrawalRecord.setUserId(userId);
        withdrawalRecord.setZfbAccountId(insertWithdrawalRecordBO.getZfbAccountId());
        withdrawalRecord.setBankAccountId(insertWithdrawalRecordBO.getBankAccountId());
        withdrawalRecord.setAmount(insertWithdrawalRecordBO.getAmount());
        withdrawalRecord.setCurrency("CNY");
        withdrawalRecord.setFeeRate(BigDecimal.ZERO);
        withdrawalRecord.setFeeAmount(BigDecimal.ZERO);
        withdrawalRecord.setChannel(insertWithdrawalRecordBO.getChannel());
        withdrawalRecord.setRequestTime(new Date());
        withdrawalRecord.setStatus(0);
        withdrawalRecord.setAuditStatus(0);
        withdrawalRecord.setWithdrawalNo(generateWithdrawalNo());
        withdrawalRecordMapper.insertWithdrawalRecord(withdrawalRecord);
        //查询用户积分
        UserPoints userPoints = pointsService.selectUserPointsByUserId(userId);
        if (ObjectUtils.isEmpty(userPoints)) {
            throw new RuntimeException("未查询到可提现积分");
        }
        //提现积分
        Integer withdrawalPoints = insertWithdrawalRecordBO.getAmount().intValue();
        if (withdrawalPoints > userPoints.getAvailablePoints()) {
            throw new RuntimeException("提现积分不足");
        }
        Integer afterWithdrawalPoints = userPoints.getTotalPoints() - withdrawalPoints;
        userPoints.setTotalPoints(afterWithdrawalPoints);
        userPoints.setAvailablePoints(afterWithdrawalPoints);
        pointsService.updateUserPoints(userPoints);
        //添加积分变更记录
        saveUserPointsLog(userId, 2, -withdrawalPoints, 1, "提现扣除积分", withdrawalRecord.getId().toString());
    }

    public List<WithdrawalRecord> selectWithdrawalRecordByUserId(Long userId) {
        return withdrawalRecordMapper.selectWithdrawalRecordByUserId(userId);
    }

    public void audit(AuditBO auditBO) {
        WithdrawalRecord withdrawalRecord = withdrawalRecordMapper.selectWithdrawalRecordById(auditBO.getId());
        Long userId = withdrawalRecord.getUserId();
        if (auditBO.getAuditStatus() == 1) {
            //根据支付宝账户id查询支付宝账户信息
            UserZfbAccount userZfbAccount = userZfbAccountService.selectUserZfbAccountById(withdrawalRecord.getZfbAccountId());
            if(ObjectUtils.isEmpty(userZfbAccount)){
                log.info("未查询到用户支付宝账户信息");
                throw new BusinessException("未查询到用户支付宝账户信息");
            }
            //模拟调用支付宝转账接口
            WapTransferBO wapTransferBo = new WapTransferBO();
            wapTransferBo.setOrderNo(withdrawalRecord.getWithdrawalNo());
            wapTransferBo.setAlipayLoginName(userZfbAccount.getZfbAccount());
            wapTransferBo.setName(userZfbAccount.getZfbName());
            //提现金额=提现积分/10
            BigDecimal withdrawalAmount = withdrawalRecord.getAmount().divide(BigDecimal.TEN, 2, RoundingMode.HALF_UP);
            wapTransferBo.setTransferAmount(withdrawalAmount);
            AlipayFundTransUniTransferResponse response = transfer(wapTransferBo);
            if("SUCCESS".equals(response.getStatus())){
                withdrawalRecord.setStatus(1);
                withdrawalRecordMapper.updateWithdrawalRecord(withdrawalRecord);
            }else{
                withdrawalRecord.setStatus(2);
                withdrawalRecord.setFailReason(response.getSubMsg());
                withdrawalRecordMapper.updateWithdrawalRecord(withdrawalRecord);
            }
        } else {
            //查询用户积分
            UserPoints userPoints = pointsService.selectUserPointsByUserId(userId);
            Integer returnPoints = withdrawalRecordMapper.selectWithdrawalRecordById(auditBO.getId()).getAmount().intValue();
            //返还用户积分
            userPoints.setTotalPoints(userPoints.getTotalPoints() + returnPoints);
            userPoints.setAvailablePoints(userPoints.getAvailablePoints() + returnPoints);
            pointsService.updateUserPoints(userPoints);
            //添加积分变更记录
            saveUserPointsLog(userId, 1, returnPoints, 1, "提现失败返还积分", auditBO.getId().toString());
        }

        withdrawalRecord.setId(auditBO.getId());
        withdrawalRecord.setAuditStatus(auditBO.getAuditStatus());
        withdrawalRecordMapper.updateWithdrawalRecord(withdrawalRecord);
    }

    public void callback() {
        //模拟支付宝回调成功
        WithdrawalRecord withdrawalRecord = new WithdrawalRecord();
        withdrawalRecord.setId(1L);
        withdrawalRecord.setStatus(1);
        withdrawalRecordMapper.updateWithdrawalRecord(withdrawalRecord);
    }

    public String generateWithdrawalNo() {
        // 生成提现订单号
        return "TX" + UUID.randomUUID().toString().replace("-", "").substring(0, 30);
    }

    //保存积分变动记录
    public void saveUserPointsLog(Long userId, Integer changeType, Integer points, Integer pointsType, String source, String relatedOrderNo) {
        //添加积分变更记录
        UserPointsLog userPointsLog = new UserPointsLog();
        userPointsLog.setUserId(userId);
        userPointsLog.setChangeType(changeType);
        userPointsLog.setChangeValue(points);
        userPointsLog.setPointsType(pointsType);
        userPointsLog.setSource(source);
        userPointsLog.setRelatedOrderNo(relatedOrderNo);
        userPointsLog.setCreateTime(new Date());
        pointsService.insertUserPointsLog(userPointsLog);
    }

    //支付宝网页转账接口
    public AlipayFundTransUniTransferResponse transfer(WapTransferBO wapTransferBo){
        //调用支付宝APP支付
        log.info("开始调用支付宝转账接口");
        try {
            return alipayFundTransUniTransferWap.wapTransfer(wapTransferBo);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}
